# == Coding: UTF-8 ==
# @Project :        BooksManagementSystem
# @fileName         stu_login.py  
# @version          v0.5
# @author           Echo
# @GiteeWarehouse   https://gitee.com/liu-long068/
# @editsession      2023/6/2
# @Software:        PyCharm
# ====/******/=====
""" 学生登录图书管理系统 """
import json


class StudentLogin:
    def __init__(self):
        self.path = r'D:\BooksManagementSystem\public\users\student.json'
        self.username = None
        self.password = None
        self.users = []
        self.load_users()

    def load_users(self):
        # 先读取已有的 JSON 文件
        try:
            with open(self.path, 'r', encoding='utf-8') as file:
                self.users = json.load(file)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f'Error loading user data: {e}')

    def save_users(self):
        try:
            with open(self.path, 'w', encoding='utf-8') as file:
                json.dump(self.users, file, ensure_ascii=False, indent=4)
        except FileNotFoundError as e:
            print(f'Error saving user data: {e}')

    def login_business(self):
        self.username = str(input('请输入用户名：'))
        self.password = str(input('请输入密码：')).lower()
        self.load_users()
        for user in self.users:
            if user['学号'] == self.username:
                if user['身份证号'][12:].lower() == self.password:  # 密码为身份证号后六位
                    if user['状态'] == 0:
                        print(f"学生【{user['姓名']}】已被禁用！请联系图书馆管理员！")
                        return False
                    elif user['状态'] == 2:
                        print(f"学生【{user['姓名']}】为图书馆黑名单！请联系图书馆管理员！")
                        return False
                    else:
                        print(f"【{user['姓名']}】， 登录成功！")
                        return user['状态']

                else:
                    count = 1
                    while count <= 5:
                        print(f"密码错误！机会还有{6 - count - 1}次！")
                        count += 1
                        self.password = str(input("请重新输入密码：")).lower()
                        if user['身份证号'][12:].lower() == self.password:
                            print(f"【{user['姓名']}】，登录成功！")
                            return user['状态']
                        else:
                            if count == 5:
                                self.update_statu(user, 0)
                                print(f"密码错误次数超过五次，学生【{user['姓名']}】已被禁用！请联系图书馆管理员！")
                                return False
                            else:
                                continue

        print("该学生不存在！")
        return False

    def update_statu(self, user, statu):
        # 更新statu
        user['状态'] = statu
        self.save_users()


